package com.mac.livedatabus

import androidx.lifecycle.BusLiveData
import com.mac.livedatabus.core.LiveDataBusCore
import java.lang.reflect.InvocationHandler
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Proxy

object LiveDataBus {
    @JvmStatic
    @Synchronized
    fun <T> getSyn(key: String): BusLiveData<T> {
        return get(key)
    }

    @JvmStatic
    fun <T> get(key: String): BusLiveData<T> {
        return LiveDataBusCore.getChannel(key)
    }

    fun <T> get(key: String, type: Class<T>): BusLiveData<T> {
        return LiveDataBusCore.getChannel(key)
    }

    @JvmStatic
    fun <E> of(clz: Class<E>): E {
        require(clz.isInterface) {
            ""
        }
        require(clz.interfaces.isEmpty()) {
            ""
        }
        return Proxy.newProxyInstance(
            clz.classLoader,
            arrayOf(clz),
            InvocationHandler { _, method, _ ->
                return@InvocationHandler get(
                    "${clz.canonicalName}_${method.name}",
                    (method.genericReturnType as ParameterizedType).actualTypeArguments[0].javaClass
                )
            }) as E
    }
}